package org.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class PlaneFrame extends JFrame {
    TextArea username;
    TextArea password;
        JButton button;
        JPanel panel;

        public PlaneFrame() {
            this.setTitle("飞机大作战");
            this.setSize(400, 600);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            init();
            this.setVisible(true);
        }

    void  init() {
        username = new TextArea("用户名");
        password = new TextArea("密码");
        button = new JButton("开始游戏");
        panel = new JPanel();
        panel.add(username);
        panel.add(password);
        panel.add(button);
        this.add(panel);
        panel.setLayout(new FlowLayout());

        button.addActionListener(e -> {

            String name = username.getText();
            String pwd = password.getText();
            String namereg = "^[a-zA-Z][a-zA-Z0-9_]{2,19}$";
            // 密码正则表达式：至少包含一个小写字母、一个大写字母和一个数字，长度至少8位
            String pwdreg = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,}$";

            if (!name.matches(namereg)) {
               JOptionPane.showMessageDialog(null, "用户名格式错误！",
                        "错误", JOptionPane.ERROR_MESSAGE);
            } else if (!pwd.matches(pwdreg)) {
                JOptionPane.showMessageDialog(null, "密码格式错误！",
                        "错误", JOptionPane.ERROR_MESSAGE);
            } else {
                try {
                    if (name.equals("admin") && pwd.equals("Admin123")) {
                        // 登录成功，隐藏当前窗口，创建新的游戏窗口
                        setVisible(false);
                        JFrame gameFrame = new JFrame("飞机大战");
                        gameFrame.setSize(400, 600);
                        gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        // 添加一个简单的标签表示游戏界面
                        gameFrame.add(new JLabel("欢迎进入游戏!", SwingConstants.CENTER));
                        gameFrame.setVisible(true);
                    } else {
                        throw new RuntimeException("用户名或密码错误");
                    }
                } catch (Exception e1) {
                    JOptionPane.showMessageDialog(null, e1.getMessage(),
                            "错误", JOptionPane.ERROR_MESSAGE);
                }

            }
        });
    }
}